<template>
  <u-comment
    :config="config"
    page
    @submit="submit"
    @like="like"
    @reply-page="replyPage"
  >
    <!-- <div>导航栏卡槽</div> -->
    <template #header>
      <span />
    </template>
    <!-- <template #info>用户信息卡槽</template> -->
    <!-- <template #card>用户信息卡片卡槽</template> -->
    <!-- <template #opearte>操作栏卡槽</template> -->
    <!-- <template #func>功能区域卡槽</template> -->
  </u-comment>
</template>

<script setup lang="ts">
import emoji from "@/assets/emoji";
import { onMounted, reactive } from "vue";
import {
  CommentApi,
  ConfigApi,
  createObjectURL,
  ReplyPageParamApi,
  SubmitParamApi,
  usePage,
  UToast
} from "undraw-ui";
import { commentsAdd, getChapterById } from "@/api/learn/comments";
import { useUserStoreHook } from "@/store/modules/user";
import dayjs from "dayjs";
import { chapterLike, userLikeList } from "@/api/learn/chapterLikes";
import { message } from "@/utils/message";

const useUserStore = useUserStoreHook();
const props = defineProps({
  chapterId: Number
});

const config = reactive<ConfigApi>({
  user: {
    id: useUserStore.id,
    username: useUserStore.username,
    avatar: import.meta.env.VITE_STATIC_URL + useUserStore.avatar,
    // 评论id数组 建议:存储方式用户uid和评论id组成关系,根据用户uid来获取对应点赞评论id,然后加入到数组中返回
    likeIds: []
  },
  emoji: emoji,
  comments: []
});

let temp_id = 100;
// 提交评论事件
const submit = async ({ content, parentId, files, finish }: SubmitParamApi) => {
  console.log("提交评论: " + content, parentId, files);

  const { data } = await commentsAdd({
    content,
    parentId: Number(parentId),
    chapterId: props.chapterId,
    uid: Number(config.user.id),
    address: "来自江苏",
    likes: 0,
    username: config.user.username,
    avatar: config.user.avatar,
    level: 6,
    homeLink: `/`
  });
  /**
   * 上传文件后端返回图片访问地址，格式以'||'为分割; 如:  '/static/img/program.gif||/static/img/normal.webp'
   */
  let contentImg = files?.map(e => createObjectURL(e)).join("||");

  temp_id += 1;
  const comment: CommentApi = {
    id: String(data.id),
    parentId: data.parentId,
    uid: data.uid,
    address: data.address,
    content: data.content,
    likes: data.likes,
    createTime: "2024-05-16",
    contentImg: contentImg,
    user: {
      username: data.username,
      avatar: data.avatar,
      level: data.level,
      homeLink: `/${data.id}`
    },
    reply: null
  };
  setTimeout(() => {
    finish(comment);
    UToast({ message: "评论成功!", type: "info" });
    refresh();
  }, 200);
};

// 点赞按钮事件 将评论id返回后端判断是否点赞，然后在处理点赞状态
const like = async (id: string, finish: () => void) => {
  console.log("点赞: " + id);
  const res = await chapterLike({
    id,
    chapterId: props.chapterId,
    userId: useUserStore.id
  });

  console.log(res);
  message(res.message, { type: "success" });
  finish();
};

async function commentsList() {
  let { data } = await getChapterById({ chapterId: props.chapterId });
  return data.map(e => {
    return {
      id: String(e.id),
      parentId: e.parentId,
      uid: e.uid,
      address: e.address,
      content: e.content,
      likes: Number(e.likes),
      createTime: dayjs(e.createdAt).format("YYYY-MM-DD HH:mm:ss"),
      user: {
        username: e.username,
        avatar: e.avatar,
        level: Number(e.level),
        homeLink: `/${e.id}`
      },
      reply: {
        total: e.reply.total,
        list: e.reply.list.map(e => {
          return {
            id: String(e.id),
            parentId: e.parentId,
            uid: e.uid,
            address: e.address,
            content: e.content,
            likes: Number(e.likes),
            createTime: dayjs(e.createdAt).format("YYYY-MM-DD HH:mm:ss"),
            user: {
              username: e.username,
              avatar: e.avatar,
              level: Number(e.level),
              homeLink: `/${e.id}`
            }
          };
        })
      }
    };
  });
}

const reply = [];

//回复分页
function replyPage({ parentId, pageNum, pageSize, finish }: ReplyPageParamApi) {
  let tmp = {
    total: 0,
    list: []
  };
  reply.forEach(item => {
    if (parentId === item.parentId) {
      tmp = {
        total: item.total,
        list: usePage(pageNum, pageSize, item.list)
      };
    }
  });
  finish(tmp);
}

function getReplyList(list) {
  let replyList = [];
  list.forEach(item => {
    replyList.push({
      total: item.reply.total,
      list: item.reply.list,
      parentId: item.id
    });
  });
  return replyList;
}

async function refresh() {
  let list = await commentsList();
  config.comments = list;
  reply.push(...getReplyList(list));
  let { data } = await userLikeList({ userId: useUserStore.id });
  console.log(data);
  if (data) {
    const likeIds = [];
    data.forEach(item => {
      likeIds.push(item.commentId);
    });
    config.user.likeIds = likeIds;
  }
}

onMounted(async () => {
  await refresh();
});
</script>
